package com.lghs.stutor;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Create extends Activity implements Alertresponder {

    // Progress Dialog
    private ProgressDialog pDialog;

    EditText inputemail, inputemailconfirm, inputusername, inputpassword, inputpasswordconfirm;
    Vital vital = new Vital();
    static String url, email, username, password, passwordreconfirm, emailreconfirm;
    InputMethodManager inputManager;
    ConnectivityManager cm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_create_account);
        declaredcomponents();
        onclicklisteners();
        inputemail.requestFocus();
    }

    public void onBackPressed() {
        super.onBackPressed();
        Intent i = new Intent(this, Login.class);
        startActivity(i);
        finish();
    }

    public void buttonhandler(int number) {
        switch (number) {
            case 1:
                createUser();
                break;
        }
    }

    @Override
    public void internethandler(int number) {
        switch (number) {
            case 1:

                email = inputemail.getText().toString().trim();
                username = inputusername.getText().toString().trim();
                password = inputpassword.getText().toString().trim();
                passwordreconfirm = inputpasswordconfirm.getText().toString().trim();
                emailreconfirm = inputemailconfirm.getText().toString().trim();
                boolean goodpass = false;
                boolean goodemail = false;
                if (email.equals(emailreconfirm) && !email.equals(""))
                    goodemail = true;
                else {
                    goodemail = false;
                    vital.alertsystem(Create.this, "Email mismatch",
                            "Emails do not match", "2", "red", "",
                            "I'll fix it!", "");

                }
                if (password.equals(passwordreconfirm) && !password.equals(""))
                    goodpass = true;
                else {
                    goodpass = false;
                    vital.alertsystem(Create.this, "Password mismatch",
                            "Passwords do not match", "2", "red", "",
                            "I'll fix it!", "");
                }

                if (goodemail && goodpass)
                    new createaccount().execute();

                break;
            case 2:
                vital.alertsystem(Create.this, "Internet Connectivity",
                        "Your internet connection seems to be missing", "13",
                        "red", "Try Again", "", "Cancel");
                break;
        }
    }

    public void declaredcomponents() {
        inputemail = (EditText) findViewById(R.id.create_edittext_email);
        inputusername = (EditText) findViewById(R.id.create_edittext_username);
        inputpassword = (EditText) findViewById(R.id.create_edittext_password);
        inputpasswordconfirm = (EditText) findViewById(R.id.create_edittext_password_reenter);
        inputemailconfirm = (EditText) findViewById(R.id.create_edittext_confirmemail);
        inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    public void onclicklisteners() {
        final Button createbutton = (Button) findViewById(R.id.create_button_create);
        createbutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                createUser();
            }
        });
    }

    public void createUser() {
        inputManager.hideSoftInputFromWindow(
                getCurrentFocus().getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
        cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        vital.checkInternetConnection(Create.this, cm);
    }

    private class createaccount extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Create.this, R.style.Theme_MyDialog);
            pDialog.setMessage("Creating Account\nPlease Wait..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.setIcon(R.drawable.idk);
            pDialog.show();
        }

        protected String doInBackground(String... urls) {
            String response = "";
            url = "http://" + vital.host + "/create.php?u=" + username + "&p="
                    + password + "&e=" + email + "";
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            try {
                HttpResponse execute = client.execute(httpGet);
                InputStream content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    response += s.trim();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }

        @Override
        protected void onPostExecute(String result) {
            pDialog.dismiss();
            if (result.contains("Account Created")) {
                Intent i = new Intent(getApplicationContext(), Login.class);
                i.putExtra("uname", username);
                i.putExtra("pass", password);
                startActivity(i);
                finish();
            } else
                vital.alertsystem(
                        Create.this,
                        "Account Creation Failed",
                        result,
                        "3", "red", "", "", "Ok :(");
        }
    }
}